package com.jhf.skypac_pda;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.elvishew.xlog.XLog;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.guanaj.easyswipemenulibrary.EasySwipeMenuLayout;
import com.jhf.skypac_pda.EventMessage.MessageEvent;
import com.jhf.skypac_pda.base.BaseActivity;
import com.jhf.skypac_pda.db.bean.DB_OperationRecord;
import com.jhf.skypac_pda.db.impl.OperationRecordDaoImp;
import com.jhf.skypac_pda.model.DialogCallback;
import com.jhf.skypac_pda.model.FeedRecord;
import com.jhf.skypac_pda.model.FinishedProductModel;
import com.jhf.skypac_pda.model.LzyResponse;
import com.jhf.skypac_pda.utils.ConstantPara;
import com.jhf.skypac_pda.utils.PrefUtils;
import com.jhf.skypac_pda.utils.Urls;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.barcode.BarcodeManager;
import com.symbol.emdk.barcode.ScanDataCollection;
import com.symbol.emdk.barcode.Scanner;
import com.symbol.emdk.barcode.ScannerConfig;
import com.symbol.emdk.barcode.ScannerException;
import com.symbol.emdk.barcode.ScannerInfo;
import com.symbol.emdk.barcode.ScannerResults;
import com.symbol.emdk.barcode.StatusData;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okgo.OkGo;
import okgo.model.HttpHeaders;
import okgo.model.Response;
import okhttp3.RequestBody;

import static com.jhf.skypac_pda.utils.ConstantPara.JSON;

/**
 * AGV入库、吹膜入库、人工入库、基材退库共用界面
 */
public class AGVStockInActivity extends BaseActivity implements EMDKManager.EMDKListener, Scanner.DataListener, Scanner.StatusListener, BarcodeManager.ScannerConnectionListener {
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.ll_empty)
    LinearLayout imgEmpty;
    @BindView(R.id.et_warehouse_position_code)
    EditText et_warehouse_position_code;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.et_pallet_code)
    TextView etPalletCode;
    @BindView(R.id.textViewRollNumber)
    TextView textViewRollNumber;
    @BindView(R.id.stop_feeding)
    TextView stopFeeding;
    @BindView(R.id.start_feeding)
    TextView startFeeding;
    @BindView(R.id.stock_in_manual)
    TextView stockInManual;
    @BindView(R.id.ll_delete)
    LinearLayout llDelete;
    @BindView(R.id.ll_delete2)
    LinearLayout llDelete2;

    private AtomicBoolean initFlag = new AtomicBoolean(false);
    private EMDKManager emdkManager = null;
    private BarcodeManager barcodeManager = null;
    private Scanner scanner = null;
    public ScannerInfo readScannerInfo;
    private boolean bSoftTriggerSelected = false;
    private boolean bExtScannerDisconnected = false;
    private final Object lock = new Object();
    private String stockInType = "";
    private List<FinishedProductModel> mList = new ArrayList<>();
    private FinishedProductListAdapter mAdapter;
    private FinishedProductModel finishedProductModel = new FinishedProductModel();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_agv_stock_in);

        stockInType = getIntent().getStringExtra("stockInType");
        if (stockInType == null) {
            stockInType = ConstantPara.STOCK_IN_TYPY_AGV;
        }

        ButterKnife.bind(this);
        //initZebra(this);
        initView();
    }

    @Override
    protected void onResume() {
        // The application is in foreground
        super.onResume();
        initZebra(this);
    }

    private void initView() {
        if (stockInType.equals(ConstantPara.STOCK_IN_TYPY_AGV)) {
            txtTitle.setText("AVG入库");
        } else if (stockInType.equals(ConstantPara.STOCK_IN_TYPY_BLOWN_FILM)) {
            txtTitle.setText("吹膜入库");
        } else if (stockInType.equals(ConstantPara.STOCK_IN_TYPY_MANUAL)) {
            txtTitle.setText("人工入库");
            startFeeding.setText("人工入库");
        } else {
            txtTitle.setText("基材退库");
            stockInManual.setVisibility(View.VISIBLE);
        }

        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvData.setLayoutManager(manager);
        mAdapter = new FinishedProductListAdapter(R.layout.stock_in_item_rv_swipemenu, mList);
        rvData.setAdapter(mAdapter);

        et_warehouse_position_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    llDelete.setVisibility(View.VISIBLE);
                } else {
                    llDelete.setVisibility(View.GONE);
                }
            }
        });

        etPalletCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    llDelete2.setVisibility(View.VISIBLE);
                } else {
                    llDelete2.setVisibility(View.GONE);
                }
            }
        });
    }

    public class FinishedProductListAdapter extends BaseQuickAdapter<FinishedProductModel, BaseViewHolder> {


        public FinishedProductListAdapter(@LayoutRes int layoutResId, @Nullable List<FinishedProductModel> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(final BaseViewHolder helper, FinishedProductModel item) {
            helper.setText(R.id.textViewRollNumber, item.getMaterialBatchCode());
            helper.setText(R.id.textViewMaterialNumber, item.getMaterialCode());
            helper.setText(R.id.textViewProductName, item.getMaterialName());
            helper.setText(R.id.textViewSpecification, item.getMaterialSpec());
            helper.setText(R.id.textViewWeight, item.getProductionReportNetWeight() + " Kg");
            helper.setText(R.id.textViewLength, item.getProductionReportLength() + " m");
            helper.getView(R.id.left).setVisibility(View.GONE);
            helper.getView(R.id.right_menu_2).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(AGVStockInActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    deleteItem(item);

                    EasySwipeMenuLayout easySwipeMenuLayout = helper.getView(R.id.es);
                    easySwipeMenuLayout.resetStatus();

                    textViewRollNumber.setText("(" + mList.size() + "/2)");
                }
            });
            /*helper.getView(R.id.content).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(FinishedProductStockInActivity.this, "setOnClickListener", Toast.LENGTH_SHORT).show();

                }
            });*/

        }

    }

    private void deleteItem(FinishedProductModel item) {
        // 从数据源中删除数据
        int position = mAdapter.getData().indexOf(item);
        mAdapter.getData().remove(item);
        mAdapter.notifyItemRemoved(position); // 通知数据源改变
    }

    public void initZebra(Context context) {
        boolean initResult = initFlag.compareAndSet(false, true);
        if (initResult) {
            XLog.i("ZEBRA初始化扫码设备");
            try {
                EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
                XLog.i("ZEBRA初始化结果" + results.statusCode);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            XLog.i("ZEBRA已经初始化");
        }

    }

    @Override
    public void onOpened(EMDKManager emdkManager) {
        this.emdkManager = emdkManager;
        // Acquire the barcode manager resources
        initBarcodeManager();
        // Enumerate scanner devices
        enumerateScannerDevices();
    }

    @Override
    public void onClosed() {
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
        }
    }

    private void initScanner() {
        if (scanner == null) {
            if (barcodeManager != null) {
                scanner = barcodeManager.getDevice(readScannerInfo);
                setDecoders();
            }
            if (scanner != null) {
                scanner.addDataListener(this);
                scanner.addStatusListener(this);
                try {
                    scanner.enable();
                } catch (ScannerException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initBarcodeManager() {
        barcodeManager = (BarcodeManager) emdkManager.getInstance(EMDKManager.FEATURE_TYPE.BARCODE);
        // Add connection listener
        if (barcodeManager != null) {
            barcodeManager.addConnectionListener(this);
        }
    }

    private void deInitBarcodeManager() {
        if (emdkManager != null) {
            emdkManager.release(EMDKManager.FEATURE_TYPE.BARCODE);
        }
    }

    private void deInitScanner() {
        if (scanner != null) {
            try {
                scanner.disable();
                scanner.removeDataListener(this);
                scanner.removeStatusListener(this);
                scanner.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
            scanner = null;
        }
    }

    private void setDecoders() {
        if (scanner != null) {
            try {
                ScannerConfig config = scanner.getConfig();
                // Set EAN8
                config.decoderParams.ean8.enabled = true;
                // Set EAN13
                config.decoderParams.ean13.enabled = true;
                // Set Code39
                config.decoderParams.code39.enabled = true;
                //Set Code128
                config.decoderParams.code128.enabled = true;
                scanner.setConfig(config);
            } catch (ScannerException e) {
                e.printStackTrace();
            }
        }
    }

    private void enumerateScannerDevices() {
        if (barcodeManager != null) {
            List<ScannerInfo> deviceList = barcodeManager.getSupportedDevicesInfo();
            XLog.i("enumerateScannerDevices size = " + deviceList.size());
            if ((deviceList != null) && (deviceList.size() != 0)) {
                Iterator<ScannerInfo> it = deviceList.iterator();
                while (it.hasNext()) {
                    ScannerInfo scnInfo = it.next();
                    XLog.i("scnInfo friendlyName=%s,isDefaultScanner=%s", scnInfo.getFriendlyName(), scnInfo.isDefaultScanner());
                    if (scnInfo.isDefaultScanner()) {
                        readScannerInfo = scnInfo;
                        deInitScanner();
                        initScanner();
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void onConnectionChange(ScannerInfo scannerInfo, BarcodeManager.ConnectionState connectionState) {
        String scannerName = "";
        String scannerNameExtScanner = scannerInfo.getFriendlyName();
        scannerName = scannerInfo.getFriendlyName();
        if (scannerName.equalsIgnoreCase(scannerNameExtScanner)) {
            switch (connectionState) {
                case CONNECTED:
                    bSoftTriggerSelected = false;
                    synchronized (lock) {
                        initScanner();
                        bExtScannerDisconnected = false;
                    }
                    break;
                case DISCONNECTED:
                    bExtScannerDisconnected = true;
                    synchronized (lock) {
                        deInitScanner();
                    }
                    break;
            }
        } else {
            bExtScannerDisconnected = false;
        }
    }

    @Override
    public void onData(ScanDataCollection scanDataCollection) {
        //if (FinishedProductStockInActivity.this.getWindow().getDecorView().getVisibility() == View.VISIBLE) {
        if ((scanDataCollection != null) && (scanDataCollection.getResult() == ScannerResults.SUCCESS)) {
            ArrayList<ScanDataCollection.ScanData> scanData = scanDataCollection.getScanData();
            for (ScanDataCollection.ScanData data : scanData) {
                XLog.i("扫码结果data = %s,type=%s", data.getData(), data.getLabelType());
                //activity.handleQrCode(data.getData());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //优先级顺序为：库位码、托盘码和入库卷信息，哪个没有填哪个，然后如果都有，且入库卷信息只有1条，再扫是第2条入库卷信息（查重）
                        // 另外有内容的情况下添加一个删除文字按钮，卷信息展示有点不好看重新搞一搞
                        if (et_warehouse_position_code.getText().toString().equals("")) {
                            et_warehouse_position_code.setText(data.getData());
                            return;
                        }

                        if (etPalletCode.getText().toString().equals("")) {
                            etPalletCode.setText(data.getData());
                            return;
                        }

                        //判断是卷号的情况下
                        if (mList != null && mList.size() < 2) {
                            if ((mList.size() == 1) && mList.get(0).getMaterialBatchCode().equals(data.getData())) {
                                Toast.makeText(AGVStockInActivity.this, "卷号重复", Toast.LENGTH_LONG).show();
                                return;
                            }
                            postRollInfo(data.getData());
                        } else {
                            Toast.makeText(AGVStockInActivity.this, "最多只能添加2卷", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        }
    }

    @Override
    public void onStatus(StatusData statusData) {
        StatusData.ScannerStates state = statusData.getState();
        switch (state) {
            case IDLE:
                // set trigger type
                if (bSoftTriggerSelected) {
                    scanner.triggerType = Scanner.TriggerType.SOFT_ONCE;
                    bSoftTriggerSelected = false;
                } else {
                    scanner.triggerType = Scanner.TriggerType.HARD;
                }
                // submit read
                if (!scanner.isReadPending() && !bExtScannerDisconnected) {
                    try {
                        scanner.read();
                    } catch (ScannerException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case WAITING:
                break;
            case SCANNING:
                break;
            case DISABLED:
                break;
            case ERROR:
                break;
            default:
                break;
        }
    }

    /*@Override
    protected void onDestroy() {
        super.onDestroy();
        deInitScanner();
        deInitBarcodeManager();
        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
            initFlag.set(false);
        }
    }*/

    @OnClick({R.id.stop_feeding, R.id.start_feeding, R.id.tv_back, R.id.stock_in_manual, R.id.ll_delete, R.id.ll_delete2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.stop_feeding:
                deInitScanner();
                deInitBarcodeManager();
                if (emdkManager != null) {
                    emdkManager.release();
                    emdkManager = null;
                    initFlag.set(false);
                }
                finish();
                break;
            case R.id.stock_in_manual:
                deInitScanner();
                deInitBarcodeManager();
                if (emdkManager != null) {
                    emdkManager.release();
                    emdkManager = null;
                    initFlag.set(false);
                }

                Intent intent = new Intent(AGVStockInActivity.this, AGVStockInActivity.class);
                intent.putExtra("stockInType", ConstantPara.STOCK_IN_TYPY_MANUAL);
                startActivity(intent);
                break;
            case R.id.tv_back:
                deInitScanner();
                deInitBarcodeManager();
                if (emdkManager != null) {
                    emdkManager.release();
                    emdkManager = null;
                    initFlag.set(false);
                }
                finish();
                break;
            case R.id.start_feeding:
                if(TextUtils.isEmpty(et_warehouse_position_code.getText().toString().trim())){

                    Toast.makeText(AGVStockInActivity.this, "库位码不能为空",Toast.LENGTH_SHORT).show();

                    return ;
                }
                if(TextUtils.isEmpty(etPalletCode.getText().toString().trim())){

                    Toast.makeText(AGVStockInActivity.this, "托盘码",Toast.LENGTH_SHORT).show();

                    return ;
                }

                if (mList == null || mList.size() ==0) {
                    Toast.makeText(AGVStockInActivity.this,"入库卷信息不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (stockInType.equals(ConstantPara.STOCK_IN_TYPY_MANUAL)) {
                    final NormalDialog dialog = new NormalDialog(this);
                    dialog.content("是否确定人工入库？")
                            .btnNum(2)
                            .btnText("取消", "确认")
                            .title("人工入库确认")
                            //.showAnim(mBasIn)//
                            //.dismissAnim(mBasOut)//
                            .show();
                    dialog.setCanceledOnTouchOutside(false);

                    dialog.setOnBtnClickL(
                            new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    dialog.dismiss();
                                }
                            },
                            new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    dialog.dismiss();
                                    postStockInManual();
                                }
                            });
                } else {
                    final NormalDialog dialog = new NormalDialog(this);
                    dialog.content("是否确定呼叫AGV入库？")
                            .btnNum(2)
                            .btnText("取消", "确认")
                            .title("呼叫AGV入库确认")
                            //.showAnim(mBasIn)//
                            //.dismissAnim(mBasOut)//
                            .show();
                    dialog.setCanceledOnTouchOutside(false);

                    dialog.setOnBtnClickL(
                            new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    dialog.dismiss();
                                }
                            },
                            new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    dialog.dismiss();
                                    postStockIn();
                                }
                            });
                }
                break;
            case R.id.ll_delete:
                et_warehouse_position_code.setText("");
                break;
            case R.id.ll_delete2:
                etPalletCode.setText("");
                break;
        }
    }

    private void postStockInManual() {
        //成功清空表单数据
        et_warehouse_position_code.setText("");
        etPalletCode.setText("");

        mList.clear();
        mAdapter.notifyDataSetChanged();
    }

    private void postStockIn() {
        Map<String ,Object> map=new HashMap<>();
        if (stockInType.equals(ConstantPara.STOCK_IN_TYPY_AGV)) {
            map.put("agvStockType", "common");
        } else if (stockInType.equals(ConstantPara.STOCK_IN_TYPY_BLOWN_FILM)) {
            map.put("agvStockType", "blown_film");
        } else if (stockInType.equals(ConstantPara.STOCK_IN_TYPY_MANUAL)) {
            map.put("agvStockType", "artificial");
        } else {
            map.put("agvStockType", "base_material");
        }

        map.put("positionCode", et_warehouse_position_code.getText().toString());
        map.put("vehicleCode", etPalletCode.getText().toString());
        ArrayList<FinishedProductModel> finishedProductModels = new ArrayList<>();
        for (FinishedProductModel finishedProductModel: mList){
            FinishedProductModel finishedProductModel1 = new FinishedProductModel();
            finishedProductModel1.setMaterialCode(finishedProductModel.getMaterialCode());
            finishedProductModel1.setMaterialBatchCode(finishedProductModel.getMaterialBatchCode());
            finishedProductModel1.setSourceCode(finishedProductModel.getSourceCode());
            finishedProductModel1.setSourceLineCode(finishedProductModel.getSourceLineCode());
            finishedProductModel1.setSourceType(finishedProductModel.getSourceType());
            finishedProductModels.add(finishedProductModel1);
        }
        map.put("taskMaterialDtoList", finishedProductModels);
        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<String>>post(Urls.URL_AGV_STOCK_IN)
                .tag(this)
                .upRequestBody(body)
                .isMultipart(false)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse<String>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<String>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                Toast.makeText(getApplicationContext(), "入库成功",Toast.LENGTH_SHORT).show();

                                //成功清空表单数据
                                et_warehouse_position_code.setText("");
                                etPalletCode.setText("");

                                mList.clear();
                                mAdapter.notifyDataSetChanged();

                                textViewRollNumber.setText("(" + mList.size() + "/2)");
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<String>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(),Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void postRollInfo(String data) {
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", PrefUtils.getString(this, "token", ""));
        OkGo.<LzyResponse<FinishedProductModel>>get(Urls.URL_GET_INPUT_STOCK_ORDER_BY_ROLL_NUM + data)
                .tag(this)
                .headers(headers)
                .execute(new DialogCallback<LzyResponse<FinishedProductModel>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<FinishedProductModel>> response) {
                        if (null != response.body().msg) {
                            if (response.body().msg.contains("成功")) {
                                finishedProductModel = response.body().data;
                                //finishedProductModel.setMaterialBatchCode(data);
                                if (finishedProductModel != null) {
                                    mList.add(finishedProductModel);
                                    mAdapter.notifyDataSetChanged();
                                }

                                textViewRollNumber.setText("(" + mList.size() + "/2)");
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<FinishedProductModel>> response) {
                        Toast.makeText(getApplicationContext(), response.getException().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShutDown(MessageEvent eventMsg) {
        String msg = eventMsg.getMessage();
        if (eventMsg.getType() == 8) {
            // activity关闭，从栈中移除
            //appManager.finishActivity(this);
            if (AGVStockInActivity.this.getWindow().getDecorView().getVisibility() == View.VISIBLE) {
                Toast.makeText(this, "登录已过期", Toast.LENGTH_SHORT).show();
                Log.i("登录过期走到这里=========", "FeedingDetailActivity");
                Intent intent = new Intent(AGVStockInActivity.this, LoginActivity.class);
                intent.putExtra("isUpdate", true);
                startActivity(intent);
            }
        }
    }
}
